<?php
require_once 'MJDMTask.php';
require_once 'MJDMUser.php';
require_once 'MJDMReward.php';

log_action("In Page : ".__FILE__);

if(!isset($_SESSION)){session_start();}

function log_action($msg) {
	$today = date("d.m.Y");
	$path = dirname(__FILE__);

	$filename = "$path"."../../logs/$today.txt";
	$fd = fopen($filename, "a");
	$str = "[" . date("d/m/Y h:i:s", mktime()) . "] " . $msg;
	fwrite($fd, $str . PHP_EOL);
	fclose($fd);
}

//check login status
function CheckLogin()
{	
	log_action("Call Funtion : " .__FUNCTION__);
		
	if(isset($_SESSION['uid']))
	{
		if(strlen($_SESSION['uid']) == 0)
		{
			ob_start();
			echo "Invalid user id!";
			header('HTTP/1.1 301 Moved Permanently');
			header("Location: ./login.htm");
			ob_end_flush();
			return FALSE;
		}
	}
	else
	{
		if(!HasUIDInCookie())
		{
			ob_start();
			echo "Login failed!";
			header('HTTP/1.1 301 Moved Permanently');
			header("Location: ./login.htm");
			ob_end_flush();
			return FALSE;
		}
	}
	
	return TRUE;
}

//check if user save uid in cookie
function HasUIDInCookie()
{
	log_action("Call Funtion : " .__FUNCTION__);
	
	if(isset($_COOKIE['uid']))
	{
		//cookie is set
		$_SESSION['uid'] = $_COOKIE['uid'];
		log_action("Cookie UID found");
		return true;
	}
	else
	{
		log_action("Cookie UID not found");
		return false;
	}

}

function SaveCookieUID($uid)
{
	log_action("Call Funtion : " .__FUNCTION__);
	
	//save cookie uid , expire time 1 year
	$expire= time()+60*60*24*30;
	setcookie("uid", $uid, $expire,"/");
}

//get userid from session
function GetSessionUID()
{		
	log_action("Call Funtion : " .__FUNCTION__);
	if(CheckLogin())
	{
		$uid = $_SESSION['uid'];
	
		return $uid;
	}
	
	return 0;
}
	
function excuteMySQLCmd($query)
{
	require 'config.php';
	
	log_action("MySQL query : " .$query);
	
	// Connecting, selecting database
	$link = mysql_connect($db_host, $db_user, $db_password)
	or log_action('Could not connect: ' . mysql_error());
	
	//echo 'Connected successfully';
	mysql_select_db($db_database) or log_action('Could not select database');
	
	mysql_set_charset('utf8',$link);
	
	$result = mysql_query($query) or log_action('Query failed: ' . mysql_error());
	
	// Closing connection
	mysql_close($link);
	
	return $result;
}

function executeScalar($query,$def="")
{
	$rs = excuteMySQLCmd($query);
	
	if (mysql_num_rows($rs)) {
		$r = mysql_fetch_row($rs);
		mysql_free_result($rs);
		return $r[0];
	}
	return $def;
}

function executeRow($query)
{
	$rs = excuteMySQLCmd($query);
	if (mysql_num_rows($rs)) {
		$r = mysql_fetch_array($rs);
		mysql_free_result($rs);
		return $r;
	}
	mysql_free_result($rs);
	return "";
}

function executeNonQuery($query)
{
	excuteMySQLCmd($query);
}

?>